package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdminMapper;
import com.heima.admin.service.AdminService;
import com.heima.common.constants.AdminConstant;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.AdUserDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.admin.AdUser;
import com.heima.model.common.vo.AdUserVo;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, AdUser> implements AdminService {
    /**
     * 用户登陆
     *
     * @param adUserDto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto adUserDto) {
        //数据校验
        if (adUserDto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询用户是否存在
        //构建查询条件
        LambdaQueryWrapper<AdUser> wrapper = Wrappers.lambdaQuery(AdUser.class).eq(AdUser::getName, adUserDto.getName());
        AdUser adUser = getOne(wrapper);
        if (adUser == null) {
            //用户不存在
            throw new CustomException(AppHttpCodeEnum.USERNAME_OR_PASSWORD_ERROR);
        }
        //校验密码
        String inputPwd = MD5Utils.encode(adUserDto.getPassword() + adUser.getSalt());
        if (!adUser.getPassword().equals(inputPwd)) {
            throw new CustomException(AppHttpCodeEnum.USERNAME_OR_PASSWORD_ERROR);
        }
        //校验账号状态
        if (adUser.getStatus() == AdminConstant.ACCOUNT_DISENABLE) {
            throw new CustomException(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        //以上校验都通过
        //生成token
        String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));
        //将当前用户信息返回
        AdUserVo adUserVo = new AdUserVo();
        BeanUtils.copyProperties(adUser, adUserVo);
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("user", adUserVo);
        return ResponseResult.okResult(data);
    }
}
